package com.example.mybaseapp.ui.flowtest

import com.example.lib_base.BaseActivity
import com.example.mybaseapp.databinding.ActivityFlowTestBinding
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch

class FlowTestActivity : BaseActivity<ActivityFlowTestBinding>() {
    val hotFlow = MutableSharedFlow<String>()

    override fun onViewInit() {
        binding.btnRedFlow.setOnClickListener {
            MainScope().launch {
                // 启动一个发射者
                MainScope(). launch {
                    repeat(3) {
                        delay(1000)
                        hotFlow.emit("Data emitted at ${System.currentTimeMillis()}")

                    }
                }

                // 第一个收集者
                MainScope().launch {
                    hotFlow.collect { data ->
                        println("热流 First collector: $data")
                        binding.txRedFlow.text = "热流 First collector: $data"

                    }
                }

                // 等待一秒后启动第二个收集者
                delay(1500)

                // 第二个收集者
                MainScope(). launch {
                    hotFlow.collect { data ->
                        println("热流 Second collector: $data")
                        binding.txRedFlow2.text = "热流 First collector: $data"
                    }
                }

                // 防止主线程结束
//                delay(5000)
            }

        }

        binding.btnColdFlow.setOnClickListener {
            MainScope().launch {
                // 第一个收集者
                launch {
                    fetchUserData().collect { data ->
                        println("冷流 First collector: $data")
                        binding.txClodFlow.text = "冷流 First collector: $data"
                    }
                }

                // 等待一秒后启动第二个收集者
                delay(1000)

                // 第二个收集者
                launch {
                    fetchUserData().collect { data ->
                        println("冷流 Second collector: $data")
                        binding.txClodFlow2.text = "冷流 First collector: $data"
                    }
                }

                // 防止主线程结束
//                delay(2000)
            }
        }
    }

    private fun fetchUserData(): Flow<String> = flow {
        // 模拟网络延迟
//        delay(1000)
        emit("User data fetched from network at ${System.currentTimeMillis()}")
    }
}